from rest_framework import serializers
from django_redis import get_redis_connection


# 序列化器的选择
class RegisterSMScodeSerializer(serializers.Serializer):

    # 校验参数　text  image_code_id

    text = serializers.CharField(min_length=4,max_length=4,required=True,label='图片验证码')
    image_code_id = serializers.UUIDField(required=True,label='uuid')

    def validate(self, attrs):

        text = attrs.get('text')
        image_code_id = attrs.get('image_code_id')

        redis_conn = get_redis_connection('code')

        redis_uuid = redis_conn.get('image_%s'%image_code_id)

        if redis_uuid is None:
            raise serializers.ValidationError('验证码过期')

        # 因为redis数据库存储的是二进制　所以要解码
        if redis_uuid.decode().upper() != text.upper():
            raise serializers.ValidationError('验证码输入错误')

        return attrs
